/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.mushroom.website.daoImpl;


import cz.muni.fi.pa165.mushroom.website.dao.ForestDao;
import cz.muni.fi.pa165.mushroom.website.entities.Forest;
import cz.muni.fi.pa165.mushroom.website.entities.Mushroom;
import cz.muni.fi.pa165.mushroom.website.entities.Visit;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Implementation of ForestDao interface
 *
 * @author Veronika Lovrantova
 */
@Repository
public class ForestDaoImpl implements ForestDao {

    @PersistenceContext
    private EntityManager em;


    public void createForest(Forest forest) {
        if (forest == null) throw new IllegalArgumentException("Forest is null");
        if (forest.getId() != null) throw new IllegalArgumentException("Forest has already assigned ID");
        if (forest.getName() == null) throw new IllegalArgumentException("Forest has no name");

        em.persist(forest);
    }

    public void updateForest(Forest forest) {
        if (forest == null) throw new IllegalArgumentException("Forest is null");
        if (forest.getId() == null) throw new IllegalArgumentException("Forest has no a ID");
        if (forest.getName() == null) throw new IllegalArgumentException("Forest has no name");


        em.merge(forest);
    }

    public void removeForest(Forest forest) {
        if (forest == null) throw new IllegalArgumentException("Forest is null");
        if (forest.getId() == null) throw new IllegalArgumentException("Forest has no a ID");
        em.remove(em.contains(forest) ? forest : em.merge(forest));        
    }

    public Forest findForest(Long id) {
        if (id == null) throw new IllegalArgumentException("ID is null");

        return em.find(Forest.class, id);
    }

    public List<Forest> listForests() {
        TypedQuery<Forest> query = em.createQuery("SELECT f from Forest f", Forest.class);

        return query.getResultList();
    }

    public List<Mushroom> listFoundMushrooms(Forest forest) {
        if (forest == null) throw new IllegalArgumentException("Forest is null");
        if (forest.getId() == null) throw new IllegalArgumentException("Forest has no a ID");
        TypedQuery<Visit> query = em.createQuery("SELECT v from Visit v WHERE v.forest=?1", Visit.class).setParameter(1, forest);

        Set<Mushroom> mushrooms = new HashSet();
        if (query != null) {
            for (Visit v : query.getResultList()) {
                mushrooms.addAll(v.getMushrooms());
            }
        }


        return new ArrayList<Mushroom>(mushrooms);

    }

}
